/* eslint-disable @typescript-eslint/no-unused-expressions */
import { getCardDetail } from "@/api/card";
import { queryOriginalImages } from "@/api/common";
import { type ResOriginalImage, type VariableCreated } from "@/api/types/commonType";
import { updateObj } from "@/utils/common";
import UseBaseCard, { type CardInfo } from "@/hooks/useBaseCard";
import { templateSelectDic } from "@/utils/dicts";
import dayjs from "dayjs";
import { find as _find } from "lodash-es";

const { cardDetailInfo } = new UseBaseCard();

export default class UseCardInfoAPI {
  private cardId: string = "";
  // 过渡字段获取图片生成参数
  private createVariable: VariableCreated = {};
  // 卡片详情，从接口抽离有用字段
  public cardDetail = reactive<CardInfo>(cardDetailInfo);
  // 一些显/隐
  public isShowObj = ref({
    cardDesc: true,
  });
  public pageLoading = ref<boolean>();

  constructor(cardId: string, initQuery = true) {
    this.cardId = cardId;

    if (initQuery) this.queryCardDetail();
  }

  // 获取卡片详情
  public queryCardDetail = async () => {
    try {
      this.pageLoading.value = true;
      const resCardDetail = await getCardDetail({ cardId: this.cardId });
      this.cardDetail = reactive(
        updateObj(this.cardDetail, resCardDetail.data as Partial<CardInfo>),
      );

      //   createVariable
      this.createVariable = JSON.parse(resCardDetail.data?.createVariable || "{}");

      // 时间
      this.cardDetail.createtime = dayjs(this.createVariable.createTime).format(
        "YYYY-MM-DD HH:mm:ss",
      );

      this.isShowObj.value.cardDesc = !(
        this.createVariable?.way?.includes("高清修复") ||
        this.createVariable?.way?.includes("涂抹消除")
      );

      // 描述
      this.cardDetail.cardDesc = this.createVariable.ui_prompt
        ? this.createVariable.ui_prompt
        : this.createVariable.prompt_zh;

      // 模板
      if (
        this.createVariable.industryKey &&
        this.createVariable.industryMinKey &&
        this.createVariable.chooseTemplate
      ) {
        const chooseTemplates =
          templateSelectDic[this.createVariable.chooseTemplate as keyof typeof templateSelectDic];
        const industrys = chooseTemplates.type.find(
          (item) => item.key == this.createVariable.industryKey,
        );
        const miniIndustrys = industrys?.list.find(
          (item) => item.key == this.createVariable.industryMinKey,
        );
        this.cardDetail.template = `${chooseTemplates.title} - ${industrys?.title} - ${miniIndustrys?.title}`;
      }

      /* 获取生成图&原图 */
      this.cardDetail.aiCreateImgs = [];
      resCardDetail.data?.imageList.forEach((item) => {
        this.cardDetail.aiCreateImgs.push({ imageUuid: item });
      });

      this.cardDetail.originalImgs = [];
      let baseUuid =
        this.createVariable.baseImageUUID ||
        this.createVariable.init_images_uuid ||
        this.createVariable.UUID ||
        this.createVariable.imageUuid1;

      // 兼容处理 TODO: createVariable 抽出
      if (!baseUuid && this.createVariable.alwayson_scripts?.controlnet?.args?.length) {
        baseUuid =
          _find(
            this.createVariable.alwayson_scripts.controlnet.args,
            (item: any) => item.module === "canny",
          )?.UUID || "";
      }

      baseUuid &&
        this.cardDetail.originalImgs.push({
          imageUuid: baseUuid,
        });

      const secondUuid = this.createVariable.imageUuid2;
      secondUuid &&
        this.cardDetail.originalImgs.push({
          imageUuid: secondUuid,
        });

      // 根据图片uuid获取原图信息
      if (this.cardDetail.aiCreateImgs.length || this.cardDetail.originalImgs.length) {
        const aiCreateUuids = this.cardDetail.aiCreateImgs?.map((item) => item?.imageUuid || "");
        const originalUuid = this.cardDetail.originalImgs?.map((item) => item?.imageUuid || "");
        const imgData = await this.queryImageInfo([...aiCreateUuids, ...originalUuid]);
        const imgMap = new Map();
        imgData.forEach((item) => {
          imgMap.set(item.imageUuid, item);
        });

        // 生成图
        this.cardDetail.aiCreateImgs = this.updateArray(
          this.cardDetail.aiCreateImgs,
          imgMap,
          "imageUuid",
        );
        // 原图
        this.cardDetail.originalImgs = this.updateArray(
          this.cardDetail.originalImgs,
          imgMap,
          "imageUuid",
        );
      }

      console.log(this.createVariable);
    } catch (error) {
      console.error(error);
    } finally {
      this.pageLoading.value = false;
    }
  };

  // 获取原图、创作生成图信息
  public queryImageInfo = (imgIds: string[]) => {
    return new Promise<ResOriginalImage[]>(async (resolve, reject) => {
      try {
        const data = await queryOriginalImages(imgIds);
        resolve((data?.data || []) as ResOriginalImage[]);
      } catch (error) {
        reject(error);
      }
    });
  };

  // 更新图片信息
  private updateArray = (arr: any[], sumMap: Map<string, Record<string, any>>, id: string) => {
    return arr.map((item) => {
      const matchedData = sumMap.get(item[id]);
      if (matchedData) {
        // 合并属性：保留原对象的属性
        return { ...item, ...matchedData };
      }
      return item;
    });
  };
}
